package com.zzxx.wechat.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zzxx.wechat.common.enums.DiscountPriceEnum;
import com.zzxx.wechat.common.enums.PriceEnum;
import com.zzxx.wechat.dao.CommodityDao;
import com.zzxx.wechat.dao.NewCommodityAddressDao;
import com.zzxx.wechat.entity.Commodity;
import com.zzxx.wechat.entity.NewCommodityAddress;
import com.zzxx.wechat.service.NewCommodityService;
import com.zzxx.wechat.service.api.WechatService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class NewCommodityServiceImpl implements NewCommodityService {


    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WechatService wechatService;

    @Autowired
    NewCommodityAddressDao newCommodityAddressDao;
    @Autowired
    CommodityDao commodityDao;
    @Value("${new.commodity.notice.template.id}")
    private String newCommodityNoticeTemplateId;

    public void queryNewGoodsTask() {
        List<NewCommodityAddress> newCommodityAddresses = newCommodityAddressDao.list();

        for (NewCommodityAddress newCommodityAddress : newCommodityAddresses) {
            String source = HttpUtil.get(newCommodityAddress.getCrawlerUrl());
            if (StringUtils.isEmpty(source)) {
                return;
            }
            log.info("查询新品接口返回:{}", source);
            JSONObject sourceJSON = JSONObject.parseObject(source);
            JSONArray commodityArray = sourceJSON.getJSONObject("response").getJSONArray("docs");
            List<Commodity> currCommodityList = buildCommodities(commodityArray, newCommodityAddress);
            List<String> pIdList = commodityDao.queryByNewCommodityAddressId(newCommodityAddress.getId()).stream().map(Commodity::getPid).collect(Collectors.toList());
            List<Commodity> needAddCommodityList = currCommodityList.stream().filter(x -> !pIdList.contains(x.getPid())).collect(Collectors.toList());
            log.info("{}查询到新品：{}", newCommodityAddress.getCountry(), JSON.toJSONString(needAddCommodityList));
            commodityDao.saveBatch(needAddCommodityList);
            for (Commodity commodity : needAddCommodityList) {
                sendNotice(newCommodityAddress.getUrl(), commodity);
            }
        }
    }

    private List<Commodity> buildCommodities(JSONArray commodityArray, NewCommodityAddress newCommodityAddress) {
        List<Commodity> currCommodityList = new ArrayList<>();


        for (int i = 0; i < commodityArray.size(); i++) {
            JSONObject commodityJSON = commodityArray.getJSONObject(i);
            Commodity commodity = new Commodity();
            commodity.setPid(commodityJSON.getString("pid"));
            commodity.setTitle(commodityJSON.getString("title"));
            commodity.setDescription(commodityJSON.getString("description"));
            commodity.setGender(commodityJSON.getString("gender"));
            commodity.setIsPro(commodityJSON.getBoolean("is_pro"));
            commodity.setIsNew(commodityJSON.getBoolean("is_new"));
            commodity.setIsRevised(commodityJSON.getBoolean("is_revised"));

            String priceName = PriceEnum.getCodeByCountry(newCommodityAddress.getCountry());
            if (StringUtils.isNotBlank(priceName)) {
                commodity.setPrice(commodityJSON.getBigDecimal(priceName));
            }
            String discountPriceName = DiscountPriceEnum.getCodeByCountry(newCommodityAddress.getCountry());
            if (StringUtils.isNotBlank(discountPriceName)) {
                commodity.setDiscountPrice(commodityJSON.getBigDecimal(discountPriceName));
            }

            commodity.setSlug(commodityJSON.getString("slug"));
            commodity.setAnalyticsName(commodityJSON.getString("analytics_name"));
            commodity.setThumbImage(commodityJSON.getString("thumb_image"));
            commodity.setNewCommodityAddressId(newCommodityAddress.getId());
            currCommodityList.add(commodity);
        }
        return currCommodityList;
    }


    private void sendNotice(String url, Commodity commodity) {
        try {
            WxMpUserList wxMpUserList = wxMpService.getUserService().userList();
            List<String> openIds = wxMpUserList.getOpenids();
            //  List<String> openIds = Arrays.asList("oUlZr6-o5K6cWM43elAEuIZ3IEtQ");
            for (String openId : openIds) {
                List<WxMpTemplateData> wxMpTemplateDataList = new ArrayList<>();
                wxMpTemplateDataList.add(new WxMpTemplateData("thing19", "监控助手"));
                wxMpTemplateDataList.add(new WxMpTemplateData("thing11", "有商品上新"));
                wxMpTemplateDataList.add(new WxMpTemplateData("thing22", truncateString(commodity.getTitle())));
                wechatService.sendTemplateMessage(openId, newCommodityNoticeTemplateId, url, wxMpTemplateDataList);
            }
        } catch (WxErrorException e) {
            log.info("发送通知报错：", e);
        }
    }

    /**
     * 微信thing最多支持20字符
     */
    private String truncateString(String input) {
        if (input != null && input.length() > 20) {
            return input.substring(0, 20);
        } else {
            return input;
        }
    }
}
